package com.fingard.dsp.bank.directbank.cqcb01;


import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.cqcb01.CQCB01Base;
import com.fingard.dsp.bank.directbank.cqcb01.CQCB01Header;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CQCB01SinglePay extends CQCB01Base implements ISinglePay {
	
	//单笔支付，不需采用流处理方式
	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception{
		//返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail tmpRetDetail;
		tmpRetDetail = d_190802(p_req1908);
		if(tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)){
			tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
		}
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	//190802对外支付
	private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception{
		RetAtsSglDetail retDetail = new RetAtsSglDetail();
		CQCB01Header bankHeader = new CQCB01Header();
		if(!p_req1908.singleDetail.isPrivate.equals("1")) {
			if (p_req1908.singleDetail.sameBnk.equals("1")) {//同行
				bankHeader.transCode = "4403";
			} else {//跨行
				if (p_req1908.singleDetail.sameCity.equals("1")) {//同城
					bankHeader.transCode = "4406";
				} else {//异城
					bankHeader.transCode = "4405";
				}
			}
		}
		else{
			retDetail.respCode = "-1";
			retDetail.respInfo = "暂不支持对私转账业务";
			return retDetail;
		}
		//发送银行之前报文主体部分送到前置机的签名端口
		StringBuffer sb = new StringBuffer();
		sb.append("<body><trans>");
		if(!p_req1908.singleDetail.isPrivate.equals("1")) {
			sb.append("<FromAcctNo>"+p_req1908.singleDetail.payAct+"</FromAcctNo><FromAcctName>"+p_req1908.singleDetail.payName+"</FromAcctName><ToAcctNo>"+p_req1908.singleDetail.recAct+"</ToAcctNo><ToAcctName>"+p_req1908.singleDetail.recName+"</ToAcctName>");
			if (p_req1908.singleDetail.sameBnk.equals("1")) {
				;
			} else {
				String[] tmpPC = p_req1908.singleDetail.getOppProvinceAndCity();
				sb.append("<ToBank>"+ p_req1908.singleDetail.recBankName+"</ToBank><ToProvince>"+tmpPC[0]+"</ToProvince><ToCity>"+tmpPC[1]+"</ToCity><ToBankCode>"+ p_req1908.singleDetail.cnapsCode+"</ToBankCode>");
			}
			sb.append("<Amount>"+p_req1908.singleDetail.payAmount+"</Amount>");
			if (p_req1908.singleDetail.sameBnk.equals("1")) {
				;
			}
			else {
				if (p_req1908.singleDetail.sameCity.equals("1")) {//同城
					String transType = "";
					transType = "1";
					sb.append("<TransType>" + transType + "</TransType>");
				} else {//异城
					//转账方式包括: 0 行内转账 1 同城交换 2 小额支付 4 大额支付（新网银此字段可默认输入4）
					String transType = "";
					if (p_req1908.singleDetail.isLargeAmt()) {
						transType = "4";
					} else if (p_req1908.singleDetail.paySpd.equals("1")) {//加急走大额
						transType = "4";
					} else {
						transType = "2";
					}
					sb.append("<TransType>" + transType + "</TransType>");
				}
			}
			String OrderId = reqHeader.reqSeqID;
			/*if(OrderId.startsWith("0")){//银行的查询号id不能为0开头
				OrderId = "1"+OrderId.substring(1);
			}*/
			int orderId = Integer.parseInt(OrderId,36);
			sb.append("<Summary>" + p_req1908.singleDetail.abstractATS + "</Summary><TransPwd>" + bankFront.loginPasswd + "</TransPwd><OrderId>" + orderId + "</OrderId></trans></body>");
		   //tmpXElement.addChild(new XElement("clientID",p_req1908.singleDetail.askNumber));客户号先放着
		}
		int length = sb.toString().getBytes().length;
		String qmhead="http://192.168.0.133/servlet/CQBANK.Trans HTTP/1.0\r\nAccept:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint,application/vnd.ms-excel,application/msword, */*\r\nReferer: http://192.168.0.133/CQBANKB2E.htm\r\nAccept-Language: zh-cn\r\nContent-Type: INFOSEC_SIGN/1.0\r\nProxy-Connection: Keep-Alive\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\nHost: 192.168.0.133\r\n";
		String qmlength="Content-Length:"+" "+String.valueOf(length)+"\r\n\r\n";
		//	构造的最终串
		String qm=qmhead+qmlength+sb.toString();
		String[] tmpSign = sendToBankSignXml(qm);
		if(tmpSign[0].length()==0) {
			String signature = "";
			String body = "";
			String aa = "<result>";
			int i = tmpSign[1].indexOf(aa);
			if (i != -1) {
				body = tmpSign[1].substring(i + 8, i + 9);
			}
			if (body.equals("0")) {
				String ab = "<sign>";
				String ac = "</sign>";
				int ib = tmpSign[1].indexOf(ab);
				int ic = tmpSign[1].indexOf(ac);
				//以下为最终的签名结果
				signature = tmpSign[1].substring(ib + 6, ic);
			}
			else{
				retDetail.respCode = "-1";
				retDetail.respInfo = tmpSign[1];
				return retDetail;
			}

			XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
			//写入报文头部信息
			writeCommonHeader(xmlWriter, bankHeader);
			xmlWriter.writeElementString("signature", signature);
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();//写入报文完成

			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				//解析银行返回
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String errorMsg = tmpBkReader.getFirstText("/out/head/ErrorMsg");
					String errorCode = tmpBkReader.getFirstText("/out/head/ErrorCode");
					retDetail.respCode = "0";
					retDetail.respInfo = errorMsg;
					retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
					retDetail.transState = errorCode;
					retDetail.payInfoCode = retDetail.transState;
					retDetail.transAmt = tmpBkReader.getFirstText("/out/body/Trans/Amount");
				} else {
					retDetail.respCode = "-1";
					retDetail.respInfo = tmpSbMsg.toString();
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
				retDetail.respCode = "0";
				retDetail.respInfo = tmpStrRet[1];
				retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
				retDetail.transState = PaymentState.FAIL_Payment;
				retDetail.payInfoCode = tmpStrRet[0];
			} else {
				retDetail.respCode = "-1";
				retDetail.respInfo = tmpStrRet[1];
			}
		}
		else {
			retDetail.respCode = "-1";
			retDetail.respInfo = tmpSign[1];
		}
		return retDetail;
	}
		
	//1944 状态查询
	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception{
		//返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		
		RetAtsSglDetail retDetail = new RetAtsSglDetail();
		CQCB01Header bankHeader = new CQCB01Header();
		bankHeader.transCode = "4407";
		String bodycontent = "";
		//发送银行之前报文主体部分送到前置机的签名端口
		String OrderId = reqHeader.reqSeqID;
		/*if(OrderId.startsWith("0")){//银行的查询号id不能为0开头且为纯数字
			OrderId = "1"+OrderId.substring(1);
		}*/
		int orderId = Integer.parseInt(OrderId,36);
		bodycontent="<body><trans><OrderId>"+orderId+"</OrderId></trans></body>";
		int length=bodycontent.getBytes().length;
		//	以下2行为签名前置服务器要求送的串，qmhead无需修改
		String qmhead="http://192.168.0.133/servlet/CQBANK.Trans HTTP/1.0\r\nAccept:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint,application/vnd.ms-excel,application/msword, */*\r\nReferer: http://192.168.0.133/CQBANKB2E.htm\r\nAccept-Language: zh-cn\r\nContent-Type: INFOSEC_SIGN/1.0\r\nProxy-Connection: Keep-Alive\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\nHost: 192.168.0.133\r\n";
		String qmlength="Content-Length:"+" "+String.valueOf(length)+"\r\n\r\n";
		bodycontent = qmhead+qmlength+bodycontent;
		try{
			String[] tmpSign = sendToBankSignXml(bodycontent);
			if(tmpSign[0].length()==0) {
				String signature = "";
				String body = "";
				String aa = "<result>";
				int i = tmpSign[1].indexOf(aa);
				if (i != -1) {
					body = tmpSign[1].substring(i + 8, i + 9);
				}
				if (body.equals("0")) {
					String ab = "<sign>";
					String ac = "</sign>";
					int ib = tmpSign[1].indexOf(ab);
					int ic = tmpSign[1].indexOf(ac);
					//以下为最终的签名结果
					signature = tmpSign[1].substring(ib + 6, ic);
				} else {//签名数据返回数据为空
					retAts.writeRespCode("-1");
					retAts.writeRespInfo(tmpSign[1]);
					retAts.writeRetDetail(retDetail);
					return retAts;
				}
				XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
				writeCommonHeader(xmlWriter, bankHeader);//写入通用的头部节点
				xmlWriter.writeElementString("signature", signature);
				xmlWriter.writeEndElement();
				xmlWriter.writeEndDocument();
				String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
				if (tmpStrRet[0].length() == 0) {
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
					if (tmpBkReader != null) {
						String tmpStatus = tmpBkReader.getFirstText("/out/head/ErrorCode");
						String tmpStatusText = tmpBkReader.getFirstText("/out/head/ErrorMsg");
						if (tmpStatus != null && isActiveRetCode(tmpStatus)) {
							String tStatus = tmpBkReader.getFirstText("/out/body/Trans/Tstatus");
							String failureRea = tmpBkReader.getFirstText("/out/body/Trans/FailureRea");
							retDetail.reqSeqID = p_req1944.askNumber;
							retDetail.respCode = "0";
							retDetail.respInfo = failureRea;
							retDetail.payInfoCode = tmpStatus+"+"+tStatus;
							retDetail.transState = tmpStatus+"+"+tStatus;
							retDetail.transAmt = tmpBkReader.getFirstText("/out/body/Trans/Amount");
						} else {
							retDetail.respCode = "-1";
							retDetail.respInfo = tmpStatusText;
						}
					} else {
						retDetail.respCode = "-1";
						retDetail.respInfo = tmpSbMsg.toString();
					}
				} else {
					retDetail.respCode = "-1";
					retDetail.respInfo = tmpStrRet[1];
				}
			}
			else {
				retDetail.respCode = "-1";
				retDetail.respInfo = tmpSign[1];
			}
		}
		catch (Exception e) {
			retDetail.respCode = "-1";
			retDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		retAts.writeRetDetail(retDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
